import type { FormInstance } from 'element-plus'
import type { ValuesType, SelectAddressState } from '../data/typings'
import { defineComponent, ref, reactive } from 'vue'
import { uniqWith } from 'lodash'
import { ElRow, ElCol, ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElLink } from 'element-plus'
import AliIcon from '~/components/AliIocn'
import MapView from '../../assetManagement/components/map/MapViewLamp'
import useVuexGetters from '~/hooks/useVuexGetters'
import { GUTTER } from '~/utils/const'
import styles from '../index.module.scss'

export default defineComponent({
  name: 'MapLocation',
  props: ['detail'],
  setup(props, { expose }) {
    const ruleFormRef = ref<FormInstance>()
    const mapViewRef = ref() // 地图
    const selectAddressRef = ref<string>() // 搜索地址
    const formValues = reactive<ValuesType>(
      props?.detail
        ? {
            id: props.detail?.id, // 行id
            address: props.detail?.address, // 显示的地址
            addressCoordinates: props.detail?.lat && `${props.detail?.lat},${props.detail?.lon}`, // 显示坐标
            regionName: props.detail?.regionName, // 所属地区
            lon: props.detail?.lon, // 经度
            lat: props.detail?.lat // 纬度
          }
        : {}
    )
    // let timer: any = null // 定时器专用timer

    const state = reactive<SelectAddressState>({
      marker: {
        lng: formValues.lon ?? undefined,
        lat: formValues.lat ?? undefined
      },
      satelliteChangingOverShow: false
    })
    const userState = useVuexGetters('user', ['userAddressInfo'])

    // 故障地点搜索
    const remoteMethod = (value: string) => {
      if (value !== '') {
        state.loading = true
        // clearTimeout(timer)
        // timer = setTimeout(() => {
        mapViewRef.value.aMapRef.plugin(['AMap.PlaceSearch'], () => {
          const plcceSearch = new mapViewRef.value.aMapRef.PlaceSearch({
            pageIndex: 1, // 页码
            pageSize: 20, // 单页显示结果条数
            // city: '武汉'
            city: userState.userAddressInfo.value.city,
            citylimit: false
          })
          plcceSearch.search(value, (status: string, result: Record<string, any>) => {
            // 搜到的数据
            state.loading = false
            state.defectAddressSelectList =
              status === 'complete' && result.info === 'OK'
                ? uniqWith(
                    result.poiList.pois,
                    (item: { name: string }, nextItem: { name: string }) =>
                      item.name === nextItem.name
                  )
                : []
          })
        })
        // }, 200)
      }
    }

    // 选择后标点
    const addressChange = (value: string) => {
      state.defectAddressSelectList?.forEach((item) => {
        if (item.name === value) {
          formValues.addressCoordinates = item.location.lng
            ? `${item.location.lng},${item.location.lat}`
            : ''
          state.marker = item.location ? { lng: item.location.lng, lat: item.location.lat } : {}
          const timer = setTimeout(() => {
            mapViewRef.value.setMarkersByPropsMarkers()
            clearTimeout(timer)
          }, 0)
        }
      })
    }

    // 修改经纬度回调
    const handleChangeAddressCoordinates = (value: string) => {
      selectAddressRef.value = undefined
      formValues.address = undefined
      state.marker = value?.includes(',')
        ? {
            lng: parseFloat(formValues.addressCoordinates?.split(',')[0]!),
            lat: parseFloat(formValues.addressCoordinates?.split(',')[1]!)
          }
        : undefined

      if (!state.marker) mapViewRef.value.clearCurrentMarker()
      // 只有新增的可打点一次, 此外均不可打点, 所以这段暂注释掉
      // const addressArr = formValues.addressCoordinates?.split(',') ?? []
      // const addressObj = {
      //   lnglat: {
      //     lng: addressArr[0],
      //     lat: addressArr[1]
      //   }
      // }
      // setTimeout(() => {
      //   mapViewRef.value.handleClickAMapCallback(addressObj)
      // }, 100)
    }

    // 根据经纬度回传得到的汉字地址
    const changeAddress = (address: any) => {
      formValues.address = address.defectAddress
      formValues.regionName = address.region
      formValues.addressCoordinates = address.longitude
        ? `${address.longitude},${address.latitude}`
        : ''
    }

    //  卫星地图切换
    const satelliteChangingOver = () => {
      state.satelliteChangingOverShow = !state.satelliteChangingOverShow
      mapViewRef.value.satelliteChangingOver(state.satelliteChangingOverShow)
    }

    expose({ ruleFormRef, formValues })

    return () => (
      <>
        <MapView
          id={styles['map-location-lamp']}
          ref={mapViewRef}
          clickon
          marker={state.marker}
          onChangeAddress={changeAddress}
        />
        {/* 卫星地图切换 */}
        <div
          class={{
            [styles['satellite-changing-over']]: true,
            [styles['satellite-changing-over-actions']]: state.satelliteChangingOverShow
          }}
          onClick={satelliteChangingOver}
        >
          <AliIcon type="icon-a-weixinghangtiantianwen1" />
          &nbsp;卫星
        </div>
        {/* <div class={styles['map-location-lamp-select-address']}> */}
        <ElFormItem class={styles['map-location-select-address']}>
          <ElSelect
            v-model={selectAddressRef.value}
            filterable
            suffixIcon={<AliIcon type="icon-sousuo" />}
            remote
            defaultFirstOption
            clearable
            remoteMethod={remoteMethod}
            onChange={addressChange}
            placeholder="请输入地址"
            // reserveKeyword
            // placeholder="请输入后选择设备地址"
            // filterMethod={remoteMethod}
            // onChange={addressChange}
            loading={state.loading}
            // clearable
          >
            {state.defectAddressSelectList?.map((item) => (
              <ElOption
                label={item.name}
                value={item.name}
                class={styles['map-location-option-address']}
                // class={styles['map-location-lamp-option-address']}
              >
                <ElLink underline={false} type="info">
                  <AliIcon type="icon-ditudingwei" />
                </ElLink>
                <section class="option-text">
                  <b>{item?.name}</b>
                  <p>{item?.address}</p>
                </section>
                {/* <ElRow>
                  <ElLink underline={false} class={styles['map-location-lamp-option-link']}>
                    <AliIcon type="icon-ditudingwei" />
                  </ElLink>
                  <div class={styles['map-location-lamp-option-line']}>
                    <span class={styles['map-location-lamp-option-name']}>{item?.name}</span>
                    <div class={styles['map-location-lamp-option-grayFont']}>{item?.address}</div>
                  </div>
                </ElRow> */}
              </ElOption>
            ))}
          </ElSelect>
        </ElFormItem>
        {/* </div> */}
        <ElForm ref={ruleFormRef} model={formValues} labelWidth={90} labelPosition="right">
          <ElRow gutter={GUTTER}>
            <ElCol span={24}>
              <ElFormItem
                prop="addressCoordinates"
                label="地址坐标"
                rules={[{ required: true, message: '请输入地址坐标"xxx,xxx"', trigger: 'blur' }]}
              >
                <ElInput
                  v-model={formValues.addressCoordinates}
                  {...{ maxlength: 50 }}
                  onChange={handleChangeAddressCoordinates}
                  clearable
                />
              </ElFormItem>
            </ElCol>
            <ElCol span={24}>
              <ElFormItem
                prop="address"
                label="详情地址"
                rules={[{ required: true, message: '请输入详情地址', trigger: 'blur' }]}
              >
                <ElInput
                  readonly
                  v-model={formValues.address}
                  suffixIcon={<AliIcon type="icon-dingwei" />}
                  {...{ maxlength: 100 }}
                  placeholder="请输入 最长100字符"
                />
              </ElFormItem>
            </ElCol>
            <ElCol span={24}>
              <ElFormItem
                prop="regionName"
                label="所属地区"
                rules={[{ required: true, message: '请输入所属地区', trigger: 'blur' }]}
              >
                <ElInput
                  readonly
                  disabled
                  v-model={formValues.regionName}
                  suffixIcon={<AliIcon type="icon-dingwei" />}
                  {...{ maxlength: 100 }}
                  placeholder="请输入 最长100字符"
                />
              </ElFormItem>
            </ElCol>
          </ElRow>
        </ElForm>
      </>
    )
  }
})
